package com.soft.javase.day09.card;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @author yzg
 * @desc TODO
 * @date 2025/4/29
 */
public class CardGame {
    private static final String[] COLORS = {"♠", "♥", "♣", "♦"};
    private static final String[] NUMBERS = {"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};
    private static final String[] JOKERS = {"小王", "大王"};

    public static void main(String[] args) {
        // 1. 创建牌堆
        List<Card> deck = createDeck();

        // 2. 洗牌
        Collections.shuffle(deck);

        // 3. 发牌
        List<Card> bottomCards = new ArrayList<>(3); // 底牌
        List<List<Card>> players = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            players.add(new ArrayList<>());
        }

        // 发51张牌给3个玩家
        for (int i = 0; i < 51; i++) {
            players.get(i % 3).add(deck.get(i));
        }

        // 剩余3张作为底牌
        for (int i = 51; i < 54; i++) {
            bottomCards.add(deck.get(i));
        }

        // 4. 确定谁可以拿底牌（谁有大王）
        int bigJoker = checkBigJoker(players);
        System.out.println("玩家" + (bigJoker + 1) + "拥有大王，获得底牌");

        // 将底牌给地主
        players.get(bigJoker).addAll(bottomCards);

        // 5. 排序每个玩家的牌
        for (List<Card> player : players) {
            Collections.sort(player);
        }
        Collections.sort(bottomCards);

        // 输出结果
        for (int i = 0; i < players.size(); i++) {
            System.out.println("玩家" + (i + 1) + "的牌: " + players.get(i));
        }
        System.out.println("底牌: " + bottomCards);
    }

    // 创建牌堆
    private static List<Card> createDeck() {
        List<Card> deck = new ArrayList<>(54);
        int index = 0;

        // 添加普通牌
        for (String number : NUMBERS) {
            for (String color : COLORS) {
                deck.add(new Card(color, number, index++));
            }
        }

        // 添加大小王
        deck.add(new Card("", JOKERS[0], index++));
        deck.add(new Card("", JOKERS[1], index));

        return deck;
    }

    // 确定地主（谁有大王）
    private static int checkBigJoker(List<List<Card>> players) {
        for (int i = 0; i < players.size(); i++) {
            for (Card card : players.get(i)) {
                if (card.getNumber().equals("大王")) {
                    return i;
                }
            }
        }
        return new Random().nextInt(3); //随机
    }
}
